package com.example.freshmenclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.freshmenclient.bean.LoginBean;
import com.example.freshmenclient.util.GainDataUtil;
import com.example.freshmenclient.util.UrlUtil;
import com.google.gson.Gson;


import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";

    private EditText etUserName;
    private EditText etPassword;
    private LoginBean loginBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initData() {
        String name = etUserName.getText().toString();
        String password = etPassword.getText().toString();
        String url = UrlUtil.basePath + "freshmenserver/user/login";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", name);
            jsonObject.put("password", password);
            GainDataUtil.gainDataForPost(this, url, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    Gson gson = new Gson();
                    Log.e(TAG, "onResponse: " + jsonObject);
                    loginBean = gson.fromJson(jsonObject.toString(), LoginBean.class);
                    if (loginBean != null && loginBean.isSuccess()) {
                        UrlUtil.major = loginBean.getData().getMajor();
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    } else {
                        Toast.makeText(LoginActivity.this, "用户名或密码错误，请重新输入！", Toast.LENGTH_SHORT).show();
                    }
                }
            }, null);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        etUserName = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
    }

    public void login(View view) {
        initData();
    }

    public void goRegist(View view) {
        startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
    }

    public void back(View view) {
        finish();
    }


}
